package cn.jdx.utils;


import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.*;


public class JdxQqMail {

    private JavaMailSenderImpl mailSender;

    public JdxQqMail(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    private final Map<String, File> fileMap = new LinkedHashMap<>();


    public void addFile(String name, File file) {
        fileMap.put(name, file);
    }


    //封装文件
    private void wrapFile(MimeMessageHelper helper) throws MessagingException {
        Set<Map.Entry<String, File>> entries = fileMap.entrySet();
        for (Map.Entry<String, File> next : entries) {
            String key = next.getKey();
            File value = next.getValue();
            helper.addAttachment(key, value);
        }
    }

    public void send(String title, String content, boolean isHTML, String from, String to) {
        MimeMessage mime = mailSender.createMimeMessage();
        try {
            //使用 MimeMessageHelper 对 mime 进行包装
            MimeMessageHelper helper = new MimeMessageHelper(mime, true); // true : 支持附件
            helper.setSubject(title);
            helper.setText(content, isHTML);// true : 识别为 html
            wrapFile(helper);
            helper.setTo(to); //发给谁
            helper.setFrom(from); //谁发的
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(mime);
    }
}
